<template>
  <div class="center">
    <el-row>
      <el-col :span="16">
        <div class="flex h-10 items-center justify-around">
          <div>伴学室名称: {{ name }}</div>
          <div>学员数: {{ student_num }}</div>
          <div>创建时间: {{ create_time }}</div>
        </div>
      </el-col>
      <el-col :span="7">
        <div class="float-right">
          <el-button type="primary" v-if="teacherStatus===0" @click="dialogVisible=true">开始伴学</el-button>
          <el-button type="primary" v-else @click="endTeachingControl">退出伴学</el-button>
          <el-button icon="el-icon-refresh-right" type="primary" @click="refresh">刷新</el-button>
        </div>
      </el-col>
    </el-row>
    <div class="flex flex-row flex-wrap">
      <div class="w-48 h-64 m-6 border-dotted border-slate-500 flex flex-col items-center pt-3" v-for="student in studentArr">
        <div class="relative left-20 text-xs -top-2" v-if="student.status==3">
          <span>请假</span>
        </div>
        <div class="relative left-20 text-xs -top-3" v-else>
          <span v-if="student.is_online==1" class="text-lime-600">待学习</span>
          <span v-else-if="student.is_online==2" class="text-lime-600">学习中</span>
          <span v-else class="text-rose-700">离线</span>
        </div>

        <div class="flex justify-between w-full">
          <div class="flex flex-col flex-wrap justify-around">
            <el-image style="width: 20px; height: 20px" src="https://jiaoguanyi008.oss-cn-shenzhen.aliyuncs.com/img/money_bag.png" @click="toMoney(student)"></el-image>
            <el-image style="width: 20px; height: 20px" src="https://jiaoguanyi008.oss-cn-shenzhen.aliyuncs.com/img/tips.png" @click="toOpenTips(student)"></el-image>
          </div>
          <el-image class="w-20 h-20" :src="student.avatar"></el-image>
          <div class="flex flex-col flex-wrap justify-around">
            <el-image v-show="student.noPeople" style="width: 20px; height: 20px" src="https://jiaoguanyi008.oss-cn-shenzhen.aliyuncs.com/img/noPeople.png" @click="openFeedback('noPeople', student)"></el-image>
            <el-image v-show="student.noClick" style="width: 20px; height: 20px" src="https://jiaoguanyi008.oss-cn-shenzhen.aliyuncs.com/img/noClick.png" @click="openFeedback('noClick', student)"></el-image>
            <el-image v-show="student.handsup" style="width: 20px; height: 20px" src="https://jiaoguanyi008.oss-cn-shenzhen.aliyuncs.com/img/greenHand.png" @click="openFeedback('handsUp', student)"></el-image>
          </div>
        </div>
        <div class="h-16 w-48 flex flex-col justify-center items-center">
          <div class="text-current text-xs leading-5">{{ student.account }}</div>
          <div class="text-current text-xs leading-5">{{ student.username }}</div>
          <div class="text-current text-xs leading-5">{{ student.gradeName }}</div>
        </div>
        <div class="flex flex-wrap content-between h-16">
          <div class="flex justify-center basis-full">
            <el-button v-if="student.is_lock===1" size="mini" @click="toOpenLock(student)">远程解屏</el-button>
            <el-button v-else size="mini" @click="toLock(student)">远程锁屏</el-button>
            <el-button size="mini" @click="toScreenShot(student)">远程截屏</el-button>
          </div>
          <div class="flex justify-center basis-full">
            <el-button size="mini" @click="toVoice(student)">远程语音</el-button>
            <el-button size="mini" @click="toVideo(student)">远程视频</el-button>
          </div>
        </div>
      </div>
    </div>
    <el-dialog title="设置课时信息" :visible.sync="dialogVisible" width="40%" :show-close="false" :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form :model="roomForm" ref="ruleForm" :rules="rules">
        <el-form-item label="课时时长:" label-width="130px" prop="class_hour">
          <el-time-picker
            is-range
            v-model="roomForm.class_hour"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            placeholder="选择时间范围"
            :default-value="value1"
            value-format="HH:mm:ss">
          </el-time-picker>
        </el-form-item>
        <el-form-item label="课时数量:" label-width="130px" prop="class_count">
          <el-select v-model="roomForm.class_count" placeholder="请选择">
            <el-option
              v-for="item in classCountOption"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学生弹窗确认:" label-width="130px" prop="open_window">
          <el-radio-group v-model="roomForm.open_window">
            <el-radio :label="1">需要</el-radio>
            <el-radio :label="-1">不需要</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelTeach">取 消</el-button>
        <el-button type="primary" @click="startTeach">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="奖励彩虹币" :visible.sync="moneyVisible" width="25%">
      <el-select v-model="money" placeholder="请选择">
        <el-option :value="3" label="3彩虹币"></el-option>
        <el-option :value="5" label="5彩虹币"></el-option>
        <el-option :value="10" label="10彩虹币"></el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
          <el-button @click="moneyVisible = false">取 消</el-button>
          <el-button type="primary" @click="addStudentMoney">发送</el-button>
      </span>
    </el-dialog>

    <div class="container-box">
      <el-dialog title="远程视频" :visible.sync="videoVisible" :before-close="closeVideo" :show-close="false" custom-class="import-dialog" :close-on-click-modal="false" :close-on-press-escape="false">
        <div class="flex">
          <div class="w-[640px] m-2.5">
            <div class="flex justify-between items-center text-sm">
              <div>账号:{{tempStudent.account}}</div>
              <div>姓名:{{tempStudent.username}}</div>
              <div>年级:{{tempStudent.gradeName}}</div>
            </div>
            <div id="remote-video" class="bg-black h-[400px] w-[640px]">
            </div>
            <div class="flex flex-col items-center" @click="closeVideo">
              <div class="w-12 h-12">
                <el-image src="https://jiaoguanyi008.oss-cn-shenzhen.aliyuncs.com/img/stopCall.png"></el-image>
              </div>
              <div class="text-black">取消</div>
            </div>
          </div>
          <div class="flex justify-around items-center flex-col">
            <el-switch v-model="mike" active-text="麦克风" @change="changeMike"></el-switch>
            <el-switch  v-model="camera" active-value="1" inactive-value="0" active-text="摄像头" inactive-text="屏幕" @change="changeCamera"></el-switch>
          </div>
        </div>
      </el-dialog>
    </div>

    <el-dialog title="远程语音" :visible.sync="voiceVisible" :before-close="closeVoice" :show-close="false" :close-on-click-modal="false" :close-on-press-escape="false">
      <audio id="remote-video" src=""></audio>
      <el-card class="flex justify-center">
        <el-form :model="tempStudent" label-width="100px">
          <el-form-item label="头像:">
            <el-avatar :src="tempStudent.avatar"></el-avatar>
          </el-form-item>
          <div class="flex w-full content-between">
            <el-form-item label="账号:">
              <span>{{tempStudent.account}}</span>
            </el-form-item>
            <el-form-item label="QID:">
              <span>{{tempStudent.qid}}</span>
            </el-form-item>
          </div>
          <div class="flex">
            <el-form-item label="姓名:">
              <span>{{tempStudent.username}}</span>
            </el-form-item>
            <el-form-item label="性别:">
              <span>{{tempStudent.sex == 1 ? '男' : '女'}}</span>
            </el-form-item>
          </div>
          <div class="flex">
            <el-form-item label="年级:">
              <span>{{tempStudent.gradeName}}</span>
            </el-form-item>
            <el-form-item label="校区:">
              <span>{{tempStudent.school}}</span>
            </el-form-item>
          </div>
          <div class="flex">
            <el-form-item label="责任教师:">
              <span>{{tempStudent.teacherName}}</span>
            </el-form-item>
          </div>
        </el-form>
      </el-card>
      <div class="flex justify-center pt-3">
        <el-image style="width: 50px;height: 50px" src="https://jiaoguanyi008.oss-cn-shenzhen.aliyuncs.com/img/stopCall.png" @click="closeVoice"></el-image>
      </div>
    </el-dialog>
    <el-dialog title="发送提醒" :visible.sync="tipsVisible" width="35%">
      <el-input v-model="tips" placeholder="请输入提醒文字"></el-input>
      <span slot="footer" class="dialog-footer">
          <el-button @click="tipsVisible = false">取 消</el-button>
          <el-button type="primary" @click="sendTips">发送</el-button>
        </span>
    </el-dialog>
    <el-dialog title="远程锁屏" :visible.sync="lockVisible" width="35%">
      <el-input v-model="lockText" placeholder="请输入锁屏界面提醒文字"></el-input>
      <span slot="footer" class="dialog-footer">
          <el-button @click="lockVisible = false">取 消</el-button>
          <el-button type="primary" @click="sendLock">发送</el-button>
      </span>
    </el-dialog>
    <el-dialog title="远程截屏" :visible.sync="screeShotVisible" width="35%" @opened="openScreenShot">
      <div class="flex justify-center w-full">
        <el-button type="primary" size="mini" @click="remoteScreenshot">远程截屏</el-button>
      </div>
      <div class="pt-3 flex justify-center w-full">
        <img id="screenImg" style="display: none"/>
      </div>
    </el-dialog>

    <el-dialog title="反馈信息" :visible.sync="feedbackVisible" width="30%">
      <span>{{ feedbackForm.feedbackText }}</span>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeFeedback">误报</el-button>
        <el-button type="primary" @click="reduceStudentMoney">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  closeRemoteVoiceVideo, endTeaching,
  getClassroom,
  getStudentByRoomId, openRemoteVoiceVideo,
  setStudentMoney,
  setStudentScreenLock, startTeaching
} from "@/api/teacher";
import mqttHandle from "@/utils/mqttHandler";
import {ZegoExpressEngine} from "zego-express-engine-webrtc";
import {generateToken04} from "@/server/zegoServerAssistant";
import pako from "pako";

var client = null;  //mqtt的实例
var zg = null
var localStream = null
export default {
  name: "index",
  data() {
    return {
      name: this.$route.query.name,
      student_num: this.$route.query.student_num,
      create_time: this.$route.query.create_time,
      roomId: this.$route.query.roomId,
      count: 0,
      teacherId: this.$route.query.teacherId,
      dialogVisible: true,
      value1: [new Date(2016, 9, 10, 8, 40), new Date(2016, 9, 10, 9, 40)],
      form: {
        class_hour: '',
        class_count: 1,
        open_window: -1
      },
      classCountOption: [
        {label: '1', value: 1},
        {label: '1.5', value: 1.5},
        {label: '2', value: 2},
        {label: '2.5', value: 2.5},
        {label: '3', value: 3},
        {label: '3.5', value: 3.5},
        {label: '4', value: 4},
        {label: '4.5', value: 4.5},
        {label: '5', value: 5}],
      rules: {
        class_hour: [{required: true, message: '请选择督学时间', trigger: 'change'}],
        class_count: [{required: true, message: '请设置课时数量', trigger: 'change'}],
        open_window: [{required: true, message: '请选择是否需要平板端弹窗确认', trigger: 'blur'}],
      },
      tipsVisible: false,
      tips: '',
      lockVisible: false,
      lockText: '',
      isLock: false, //是否在锁屏状态
      moneyVisible: false,
      money: "",
      videoVisible: false,
      mike: false, //麦克风开光
      camera: false, //摄像头开关
      voiceVisible: false,
      screeShotVisible: false,
      feedbackVisible: false,
      feedbackForm: {feedbackText: '', type: ''},
      studentForm: {},
      roomForm: {},
      studentArr: [],
      topicSends: [], //订阅的topic 例如：["Time1", "EngineMain1", "Console1", "Location1"]
      tempStudent: [],
      screenList: ['https://jiaoguanyi008.oss-cn-shenzhen.aliyuncs.com/img/16230567952784.png'],
      playStreamID: '',
      teacherStatus: 0, //0:非督学伴学状态 1：督学状态 2：伴学状态
      courseId: 0
    }
  },
  created() {
    this.createZegoExpressEngine()
    this.$nextTick(() => {
      this.getStudents()
      this.getClassroomControl()
    })
  },
  beforeDestroy() {
    this.disConnect()
    zg.logoutRoom(this.courseId.toString())
  },
  methods: {
    refresh() {
      this.getStudents()
    },
    createZegoExpressEngine() {
      zg = new ZegoExpressEngine(1160897212, "wss://webliveroom1160897212-api.imzego.com/ws");
      zg.setLogConfig({logLevel: "warn"})
      //房间内其他用户进出房间的通知
      //只有调用 loginRoom 登录房间时传入 ZegoRoomConfig，且 ZegoRoomConfig 的 userUpdate 参数为 “true” 时，用户才能收到 roomUserUpdate回调。
      zg.on('roomUserUpdate', (roomId, updateType, userList) => {
        if (updateType == 'ADD') {
          for (var i = 0; i < userList.length; i++) {
            console.log(userList[i]['userID'], '加入了房间：', roomId)
          }
        } else if (updateType == 'DELETE') {
          for (var i = 0; i < userList.length; i++) {
            console.log(userList[i]['userID'], '退出了房间：', roomId)
          }
        }
      });
      zg.on('roomStreamUpdate', async (roomId, updateType, streamList, extendedData) => {
        // 房间内其他用户音视频流变化的通知
        console.log("这是roomStreamUpdate", roomId, updateType, streamList)
        // 房间内其他用户音视频流变化的通知
        if (updateType === 'ADD') {
          //流新增,开始拉流
          for (var i = 0; i < streamList.length; i++) {
            this.playStreamID = streamList[i]['streamID']
            console.log("开始拉流", this.playStreamID, this.tempStudent.id)
            if (this.playStreamID == this.tempStudent.id) {
              await this.pullStream(streamList[i]['streamID'])
            }
          }
        } else if (updateType === 'DELETE') {
          for (var i = 0; i < streamList.length; i++) {
            console.log("这是新增流streamID", streamList[i]['streamID'])
            zg.stopPlayingStream(streamList[i]['streamID'])
          }
        }
      });
      // 注册 playerStateUpdate 拉流状态更新事件回调。
      zg.on('playerStateUpdate', ({streamID, state}) => {
        this.playStreamID = streamID
      })
      // 注册 playQualityUpdate 拉流质量更新事件回调。
      zg.on('playQualityUpdate', (streamID, stats) => {
        // stats 对象中可以拿到分辨率、帧率、码率等流质量相关信息做数据展示。
      })

      // 注册 publishQualityUpdate 推流质量更新事件回调。
      zg.on('publishQualityUpdate', ({streamID, state}) => {
        // stats 对象中可以拿到分辨率、帧率、码率等流质量相关信息做数据展示
      })
    },
    // Step3 Login room
    async loginRoom(userID, username) {
      let token = generateToken04(1160897212, userID, '946fc28a69cf45af5bccce6caa331340', 86400, '')
      const result = await zg.loginRoom(this.courseId.toString(), token, {
        userID: userID,
        userName: username
      }, {userUpdate: true})
      return result
    },
    //即构拉流
    async pullStream(streamID) {
      const remoteStream = await zg.startPlayingStream(streamID);
      // 创建媒体流播放组件
      const remoteView = zg.createRemoteStreamView(remoteStream);
      remoteView.play("remote-video", {enableAutoplayDialog: true});
    },
    //streamID 推送流ID type 1:音频通话 2:屏幕共享 3: 视频通话
    async pushStream(streamID, type) {
      let options = {camera: {video: false, audio: true}}  //音频通话
      if (type === 2) {
        options = {screen: {video: true, audio: true}}
      } else if (type === 3) {
        options = {camera: {video: true, audio: true}}
      }
      localStream = await zg.createZegoStream(options);
      zg.startPublishingStream(streamID, localStream)
    },
    startTeach() {
      let form = JSON.parse(JSON.stringify(this.roomForm))
      form.userId = localStorage.getItem("ID")
      form.teacherId = this.teacherId
      form.roomId = this.roomId
      form.type = 2
      startTeaching(form).then(res => {
        this.courseId = res.data.course_id
        this.studentArr.forEach((item, index) => {
          let topic = "/control/" + item.id + "/command"
          let now = new Date()
          let payload = {messageType: 20, timestamp: now.toJSON(), message: this.courseId};
          payload = JSON.stringify(payload)
          client.publish(topic, payload, {qos: 0, retain: true}, error => {
            if (error) {
              console.log('Publish error', error)
            }
          })
        })
        this.dialogVisible = false
        this.teacherStatus = 2
      })
    },
    endTeachingControl() {
      this.studentArr.forEach((item, index) => {
        let topic = "/control/" + item.id + "/command"
        let now = new Date()
        let payload = {messageType: 20, timestamp: now.toJSON(), message: -1};
        payload = JSON.stringify(payload)
        client.publish(topic, payload, {qos: 0, retain: true}, error => {
          if (error) {
            console.log('Publish error', error)
          }
        })
      })
      endTeaching({
        teacherId: this.teacherId,
        courseId: this.courseId,
        type: 2
      }).then(res => {
      })
      if (this.$route.name !== 'accMyClassroom') {
        this.$router.push({name: 'accMyClassroom'})
      }
    },
    cancelTeach() {
      this.dialogVisible = false
      this.$router.back()
    },
    getStudents() {
      getStudentByRoomId({
        roomId: this.roomId,
      }).then(res => {
        this.studentArr = res.data
        this.setTopic(res.data)
        this.createMqtt()
      }).catch(err => {
        this.studentArr = []
      })
    },
    getClassroomControl() {
      getClassroom({
        roomId: this.roomId
      }).then(res => {
        this.roomForm = res.data
      })
    },
    setTopic(data) {
      let that = this
      data.forEach(function (element) {
        let topic = '/control/' + element.id + '/#'
        if (!that.topicSends.includes(topic)) {
          that.topicSends.push(topic)
        }
      })
    },
    toVoice(student) {
      this.tempStudent = student
      openRemoteVoiceVideo({
        teacherId: this.teacherId,
        studentId: student.id,
        type: 1
      }).then(res => {
        let userID = "teacher" + this.teacherId
        let result = this.loginRoom(userID, userID)
        if (result === false) {
          this.$message.error("开启远程语音失败")
          return
        }
        this.pushStream(userID, 1)
        zg.on("publisherStateUpdate", ({streamID, state}) => {
          if (streamID === userID && state === "PUBLISHING") {
            setTimeout(() => {
              if (this.voiceVisible) {
                this.doPublish("command", 3, userID)
              }
            }, 100)
          }
        })
        //学生声音拉流
        this.voiceVisible = true
      })
    },
    closeVoice() {
      this.doPublish("command", 5, "")
      let streamId = "teacher" + this.teacherId
      zg.stopPublishingStream(streamId)
      zg.destroyStream(localStream)
      if (this.playStreamID !== "") {
        zg.stopPlayingStream(this.playStreamID)  //停止拉取远端推送的音视频流
      }
      zg.logoutRoom(this.courseId.toString())
      closeRemoteVoiceVideo({
        teacherId: this.teacherId,
        studentId: this.tempStudent.id,
        type: 1
      }).then(res => {
        this.voiceVisible = false
      })
    },
    toVideo(student) {
      this.tempStudent = student
      openRemoteVoiceVideo({
        teacherId: this.teacherId,
        studentId: student.id,
        type: 2
      }).then(res => {
        let userID = "teacher" + this.teacherId
        let result = this.loginRoom(userID, userID)
        if (result === false) {
          this.$message.error("开启远程视频失败")
          return
        }
        this.doPublish("command", 0, userID)
        // //自己视频推流
        // let streamId = "teacher" + this.teacherId
        // this.pushStream(streamId, 2)
        //学生视频拉流
        this.videoVisible = true
      })
    },
    closeVideo() {
      this.doPublish("command", 1, "")
      if (this.playStreamID !== "") {
        zg.stopPlayingStream(this.playStreamID)  //停止拉取远端推送的音视频流
      }
      if (this.mike) {
        let streamId = "teacher" + this.teacherId
        zg.stopPublishingStream(streamId)
        this.mike = false
      }
      if (localStream != null) {
        zg.destroyStream(localStream)
      }
      closeRemoteVoiceVideo({
        teacherId: this.teacherId,
        studentId: this.tempStudent.id,
        type: 2
      }).then(res => {
        zg.logoutRoom(this.courseId.toString())
        this.videoVisible = false
      })
    },
    decompressToImgUrl(base64Data) {
      // 将 Base64 编码的字符串解码为二进制字符串
      const binaryString = atob(base64Data);
      const byteArray = new Uint8Array(binaryString.length);
      for (let i = 0; i < binaryString.length; i++) {
        byteArray[i] = binaryString.charCodeAt(i);
      }
      // 使用pako.inflate解压缩数据
      const decompressedData = pako.inflate(byteArray, {to: 'uint8array'});
      // 创建 Blob 对象并生成 URL，以便可以在 Image 对象中使用
      const blob = new Blob([decompressedData], {type: 'image/webp'});
      return URL.createObjectURL(blob);
    },
    /**创建mqtt**/
    createMqtt() {
      var mqtt; //mqtt 处理对象（全局变量）
      //创建链接，接收数据
      if (!client) {
        mqtt = new mqttHandle(this.topicSends);
        client = mqtt.createConnect();
      }
      client.on("message", (topic, message) => {
        //数据分类
        try {
          let messageData = JSON.parse(message)
          let arr = topic.split('/')
          let studentId = arr[2]
          let type = arr[3]
          if (type === 'report') {
            switch (messageData.messageType) {
              case 200: //无人监测上报消息
                console.log("这是meaage", messageData)
                this.studentArr.forEach((item, index, arr) => {
                  if (item.id == studentId) {
                    let temp = this.studentArr[index];
                    temp.noPeople = true
                    this.studentArr.splice(index, 1, temp)
                  }
                })
                break
              case 201: //操作超时
                this.studentArr.forEach((item, index, arr) => {
                  if (item.id == studentId) {
                    let temp = this.studentArr[index];
                    temp.noClick = true
                    this.studentArr.splice(index, 1, temp)
                  }
                })
                break;
              case 202:  //解除无人检测上报
                this.studentArr.forEach((item, index, arr) => {
                  if (item.id == studentId) {
                    let temp = this.studentArr[index];
                    temp.noPeople = false
                    this.studentArr.splice(index, 1, temp)
                  }
                })
                break
              case 203: //解除操作超时上报
                this.studentArr.forEach((item, index, arr) => {
                  if (item.id == studentId) {
                    let temp = this.studentArr[index];
                    temp.noClick = false
                    this.studentArr.splice(index, 1, temp)
                  }
                })
                break;
              case 204:  //举手上报
                this.studentArr.forEach((item, index, arr) => {
                  if (item.id == studentId) {
                    let temp = this.studentArr[index];
                    temp.handsup = true
                    this.studentArr.splice(index, 1, temp)
                  }
                })
                break;
              case 205: //设备在线状态消息
                this.studentArr.forEach((item, index, arr) => {
                  if (item.id == studentId) {
                    let temp = this.studentArr[index];
                    temp.is_online = messageData.message
                    this.studentArr.splice(index, 1, temp)
                  }
                })
                break
            }
          } else if (type === 'command') {
            switch (messageData.messageType) {
              case 23: //锁屏状态
                this.studentArr.forEach((item, index, arr) => {
                  if (item.id == studentId) {
                    let temp = this.studentArr[index];
                    temp.isLock = 1
                    this.studentArr.splice(index, 1, temp)
                  }
                })
                break
              case 24: //退出锁屏状态
                this.studentArr.forEach((item, index, arr) => {
                  if (item.id == studentId) {
                    let temp = this.studentArr[index];
                    temp.isLock = 0
                    this.studentArr.splice(index, 1, temp)
                  }
                })
                break
            }
          } else if (type === 'data') {
            switch (messageData.messageType) {
              case 101: //屏幕截图图消息
                this.studentArr.forEach((item, index, arr) => {
                  if (item.id == studentId) {
                    let temp = this.studentArr[index];
                    let imageUrl = this.decompressToImgUrl(messageData.message)
                    temp.screenImg = imageUrl
                    this.studentArr.splice(index, 1, temp)
                    const element = document.getElementById("screenImg")
                    if (element) {
                      element.style.display = "block"
                      element.src = imageUrl
                    }
                  }
                })
                break;
            }
          }
        } catch (error) {
          console.log("这是error", error)
        }
      });
    },
    //停止订阅mqtt
    disConnect() {
      if (client != null) {
        client.unsubscribe(this.topicSends);
        client = null;
      }
    },
    doPublish(topicType, messageType, message, retain = false, qos = 0) {
      let topic = "/control/" + this.tempStudent.id + "/" + topicType
      let now = new Date()
      let payload = {messageType: messageType, timestamp: now.toJSON(), message: message};
      payload = JSON.stringify(payload)
      client.publish(topic, payload, {qos: 0, retain: retain}, error => {
        if (error) {
          console.log('Publish error', error)
        }
      })
    },
    toOpenTips(student) {
      this.tempStudent = student
      this.tipsVisible = true
    },
    toLock(student) {
      this.tempStudent = student
      this.lockVisible = true
    },
    toOpenLock(student) {
      this.tempStudent = student
      setStudentScreenLock({
        studentId: this.tempStudent.id,
        is_lock: 0,
      }).then(res => {
        this.doPublish("command", 24, this.lockText, true)
        this.getStudents()
        this.$message.success("发送解屏指令成功")
      }).catch(err => {
        this.$message.error("发送解屏指令失败")
      })
    },
    toScreenShot(student) {
      this.tempStudent = student
      this.screeShotVisible = true
    },
    //发送提醒
    sendTips() {
      this.doPublish("command", 50, this.tips)
      this.tipsVisible = false
    },
    sendLock() {
      setStudentScreenLock({
        studentId: this.tempStudent.id,
        is_lock: 1,
      }).then(res => {
        this.doPublish("command", 23, this.lockText, true)
        this.getStudents()
      })
      this.lockVisible = false
    },
    remoteScreenshot() {
      this.doPublish("command", 51, "")
      this.$message.success("截屏成功")
    },
    toMoney(student) {
      this.tempStudent = student
      this.moneyVisible = true
    },
    addStudentMoney() {
      if (this.money === "") {
        this.$message.info("请先选择彩虹币数量")
        return
      }
      setStudentMoney({
        studentId: this.tempStudent.id,
        type: 1,
        num: this.money
      }).then(res => {
        this.moneyVisible = false
        this.money = ""
        this.$message.success("成功")
      })
    },
    openFeedback(type, student) {
      this.tempStudent = student
      this.feedbackForm.type = type
      switch (type) {
        case 'handsUp':
          this.feedbackForm.feedbackText = "学生举手"
          break;
        case 'noClick':
          this.feedbackForm.feedbackText = "该学生三分钟未操作平板"
          break;
        case 'noPeople':
          this.feedbackForm.feedbackText = "识别到该学生三分钟未在平板前面"
          break
      }
      this.feedbackVisible = true
    },
    reduceStudentMoney() {
      this.tempStudent.handsup = false
      setStudentMoney({
        studentId: this.tempStudent.id,
        type: -1,
        num: 5
      }).then(res => {
        this.feedbackVisible = false
        this.money = ""
        this.$message.success("成功")
      })
    },
    openScreenShot() {
      document.querySelectorAll('[id="screenImg"]')[0].src = this.tempStudent.screenImg;
    },
    changeMike(status) {
      let streamId = "teacher" + this.teacherId
      if (status === true) {
        this.pushStream(streamId, 1)
        zg.on("publisherStateUpdate", ({streamID, state}) => {
          if (streamID === streamId && state === "PUBLISHING") {
            if (this.mike) {
              this.doPublish("command", 4, streamId)
            }
          }
        })
      } else {
        zg.stopPublishingStream(streamId)
        zg.destroyStream(localStream)
      }
    },
    changeCamera(status) {
      this.doPublish("command", 2, status)
    },
    closeFeedback() {
      this.feedbackVisible = false
      switch (this.feedbackForm.type) {
        case 'handsUp':
          this.tempStudent.handsup = false
          break;
        case 'noClick':
          this.tempStudent.noClick = false
          break;
        case 'noPeople':
          this.tempStudent.noPeople = false
          break
      }
    }

  }
}
</script>

<style scoped lang="scss">

.container-box {
  //弹出层的高度
  ::v-deep .el-dialog.import-dialog {
    height: auto;
    max-height: 80vh;
    overflow-y: auto;
  }

  //弹出层里内容的高度
  ::v-deep .el-dialog__body {
    max-height: 70vh !important;
  }
}


</style>
